<template>
  <view class="container">

    <view class="top-box">
      <view @click="toSearch">
        <up-input placeholder="请输入搜索关键字" border="surround" clearable prefixIcon="search" shape="circle" readonly
          customStyle="background-color: #f6f6f6;" placeholderStyle="color: #888;font-size: 28rpx;"></up-input>
      </view>
      <!-- 品牌导航 -->
      <scroll-view class="brand-nav" scroll-x>
        <view class="brand-item" v-for="(item, index) in topList" :key="index"
          :class="{ active: item.id === topTabCur }" @tap="topTabSelect(item.id)">
          {{ item.name }}
        </view>
      </scroll-view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content" @touchmove="bottomTouchMove" v-if="productGroups.length > 0">
      <!-- 左侧分类导航 -->
      <scroll-view class="category-nav" scroll-y :scroll-top="verticalNavTop">
        <view class="category-list">
          <view class="category-item" v-for="(item, index) in productGroups" :key="index"
            :class="{ active: index === tabCur }" @tap="tabSelect(index)">
            {{ item.title }}
          </view>
        </view>
      </scroll-view>

      <!-- 右侧商品列表 -->
      <scroll-view class="product-list" scroll-y :scroll-into-view="'main-' + mainCur" @scroll="verticalMain">
        <view class="product-group" v-for="(group, index) in productGroups" :key="index" :id="'main-' + index">
          <!-- 分组标题 -->
          <view class="group-header">
            <view class="group-title">
              {{ group.title }}
            </view>
            <view class="group-action" @tap="toModelDetail(group.id)">
              <text>实时行情</text>
              <u-icon name="arrow-right" size="12" color="#999"></u-icon>
            </view>
          </view>

          <!-- 商品列表 -->
          <view class="product-item" v-for="(product, pIndex) in group.skus" :key="pIndex">
            <view class="product-info">
              <view class="product-name">
                <!-- {{ group.title }}  -->
                <view>{{ product.specs }}</view>
                <view class="dateline">
                  {{ product.dateline }}
                </view>
              </view>
            </view>

            <!-- 价格列表 -->
            <view class="price-item" v-for="(quotation, qIndex) in product.colors" :key="qIndex"
              @tap="toModelDetail(group.id, quotation, product)">
              <view class="color-name">
                {{ quotation.color }}
              </view>
              <view class="price-info">
                <view class="price-value" :class="{
                  'not-updated': quotation.change_type == 'none'
                }">
                  {{ quotation.price || "暂无" }}
                </view>
                <view class="price-change" v-if="quotation.change_type != 'none'">
                  <view class="change-value" :class="{
                    up: quotation.change_type == 'inc',
                    down: quotation.change_type == 'dec',
                  }">
                    {{ quotation.change_value }}
                  </view>
                  <u-icon name="arrow-down-fill" size="8" color="#129633"
                    v-if="quotation.change_type == 'dec'"></u-icon>
                  <u-icon name="arrow-up-fill" size="8" color="#E3512B" v-else></u-icon>
                </view>

                <view v-else class="price-change">
                  <view class="change-value">
                    {{ quotation.change_value }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="main-content" v-if="productGroups.length == 0" style="align-items: center;justify-content: center;">
      <up-empty mode="data" iconSize="50"></up-empty>
    </view>

    <!-- 底部提示 -->
    <view class="bottom-tip">
      <text>灰色为当天报价未更新，点击价格可查看历史报价。</text>
    </view>

  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue'
import { brandApi } from '@/api/brand'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

onShareAppMessage(() => {
  return {
    title: '万选回收',
    path: '/pages/tabbar/menu'
  }
})

onShareTimeline(() => {
  return {
    title: '万选回收',
  }
})



// 跳转到搜索页
const toSearch = () => {
  console.log('toSearch')
  uni.navigateTo({
    url: '/pages/search'
  })
}

// 顶部品牌导航当前高亮索引
const topTabCur = ref(0)
// 左侧分类导航当前高亮索引
const tabCur = ref(0)
// 右侧主内容区当前分组索引
const mainCur = ref(0)
// 左侧分类导航滚动位置（如需联动可用）
const verticalNavTop = ref(0)

// 是否由点击触发的滚动
let isClickScrolling = false
let scrollTimeout = null

// 顶部品牌列表（模拟数据）
const topList = ref([
  { brand_name: '苹果' },
  { brand_name: '华为' },
  { brand_name: '小米' },
  { brand_name: 'OPPO' },
  { brand_name: 'vivo' },
  { brand_name: '苹果' },
  { brand_name: '华为' },
  { brand_name: '小米' },
  { brand_name: 'OPPO' },
  { brand_name: 'vivo' },
])
// 商品分组及商品数据（模拟数据）
const productGroups = ref([])

// 存储每个分组的高度，用于滚动时判断当前分组
const groupHeights = ref([])

// 计算每个分组的累计高度，便于滚动时定位
function setGroupHeights(data) {
  let heights = []
  let total = 0
  data.forEach(item => {
    total += item.height
    heights.push(total)
  })
  groupHeights.value = heights
}



// 顶部品牌导航点击切换
const topTabSelect = (id) => {
  topTabCur.value = id
  getProductList(id)
}
// 左侧分类点击切换，同时右侧主内容区联动
const tabSelect = (index) => {
  isClickScrolling = true
  tabCur.value = index
  mainCur.value = index
  clearTimeout(scrollTimeout)
  scrollTimeout = setTimeout(() => {
    isClickScrolling = false
  }, 500)
}

const windowHeight = uni.getSystemInfoSync().windowHeight
// 右侧商品列表滚动时，实时同步左侧分类高亮
const verticalMain = (e) => {
  if (isClickScrolling) {
    return
  }
  const scrollTop = e.detail.scrollTop
  const middle = scrollTop + windowHeight / 3 //以屏幕的1/3为基准
  let index = groupHeights.value.length - 1 // 默认高亮最后一个
  for (let i = 0; i < groupHeights.value.length; i++) {
    if (middle < groupHeights.value[i]) {
      index = i
      break
    }
  }
  tabCur.value = index
  mainCur.value = index
}

// 跳转到实时行情
const toModelDetail = (group_id, quotation, product) => {
  // 先获取已有的规格详情（数组），如果没有则用空数组
  let specs = []
  if (product) {
    specs = Array.isArray(product?.specs_detail) ? product.specs_detail : []
  }
  // 添加当前选中的颜色
  if (quotation) {
    specs.push({
      spec_id: quotation?.spec_id,
      spec_value_id: quotation?.spec_value_id,
      spec_value: quotation?.color
    })
  }
  console.log(specs, "specs")
  uni.navigateTo({
    url: `/pages/subPages/index?goodsId=${group_id}&specDetail=${JSON.stringify(specs)}`,
  })
}

// 获取商品列表
const getProductList = async (id) => {
  try {
    const res = await brandApi.getProductList({
      brand_id: id
    })
    productGroups.value = res.data
    if (res.data.length > 0) {
      tabCur.value = 0
      mainCur.value = 0
    }
    await nextTick()
    uni.createSelectorQuery()
      .selectAll('.product-group')
      .boundingClientRect(data => {
        setGroupHeights(data)
      })
      .exec()
  } catch (error) {
    console.log(error, "error")
  }
}


// 获取顶部品牌菜单
const getBrandList = async () => {
  try {
    const res = await brandApi.getBrandList()
    topList.value = res.data
    if (res.data.length > 0) {
      topTabCur.value = res.data[0].id
      getProductList(topTabCur.value)
    }
  } catch (error) {
    console.log(error, "error")
  }
}





// 页面挂载后，获取所有分组的高度，兼容 H5 和小程序
onMounted(() => {
  getBrandList()
  nextTick(() => {
    // #ifdef H5
    const instance = getCurrentInstance()
    uni.createSelectorQuery()
      .in(instance.proxy)
      .selectAll('.product-group')
      .boundingClientRect(data => {
        setGroupHeights(data)
      })
      .exec()
    // #endif
    // #ifndef H5
    uni.createSelectorQuery()
      .selectAll('.product-group')
      .boundingClientRect(data => {
        setGroupHeights(data)
      })
      .exec()
    // #endif
  })
})




</script>

<style lang="scss" scoped>
@import '@/index.scss';


.container {
  height: calc(100vh - 48rpx);
  background: $main-bg;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .top-box {
    padding: 20rpx 32rpx 0;
    background-color: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
  }

  .brand-nav {
    white-space: nowrap;
    padding: 20rpx 0;

    .brand-item {
      display: inline-block;
      padding: 0 30rpx;
      font-size: 28rpx;
      color: #333;
      position: relative;
      height: 70rpx;
      font-weight: 500;

      &.active {
        &::before {
          position: absolute;
          bottom: 0rpx;
          left: 50%;
          transform: translateX(-50%);
          content: '';
          display: block;
          z-index: 1;
          width: 32rpx;
          height: 8rpx;
          background: #E3512B;
          border-radius: 6rpx;
        }
      }
    }
  }

  .main-content {
    display: flex;
    flex: 1;
    overflow: scroll;
    padding: 16rpx 0;

    .category-nav {
      width: 240rpx;
      height: 100%;
      background: $main-bg;


      .category-list {
        display: flex;
        flex-direction: column;
        .category-item {
          padding: 28rpx 10rpx;
          font-size: 28rpx;
          color: #666;
          text-align: center;
          background: $white;
          border-radius: 0rpx 16rpx 16rpx 0rpx;
          flex: 1;
          width: 100%;
          // white-space: nowrap;
          // overflow: hidden;
          // text-overflow: ellipsis;
          box-sizing: border-box;

          &.active {
            color: #666;
            font-weight: 500;
            background: $light;
          }
        }
      }
    }

    .product-list {
      flex: 1;
      height: 100%;
      margin-left: 16rpx;

      .product-group {
        background: $white;
        border-radius: 12rpx;
        margin-bottom: 20rpx;

        .group-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20rpx;
          border-bottom: 1rpx solid #f5f5f5;

          .group-title {
            display: flex;
            align-items: center;
            font-size: 28rpx;
            font-weight: bold;
            color: #000;

            &::before {
              content: '';
              display: inline-block;
              width: 12rpx;
              height: 32rpx;
              background: $primary;
              border-radius: 6rpx;
              margin-right: 12rpx;
            }

          }

          .group-action {
            font-size: 22rpx;
            color: #666;
            display: flex;
            align-items: center;

            .action-icon {
              width: 14rpx;
              height: 24rpx;
              margin-left: 10rpx;
            }
          }
        }

        .product-item {
          padding: 20rpx;
          background: $white;

          .product-info {
            margin-bottom: 20rpx;

            .product-name {
              font-size: 32rpx;
              font-weight: 600;
              color: #000;
              margin-bottom: 10rpx;
              .dateline {
                font-size: 22rpx;
                color: #666;
                margin:10rpx 0;
              }
            }

            .product-desc {
              display: flex;
              justify-content: space-between;
              align-items: center;

              .desc-text {
                font-size: 22rpx;
                color: #222;
              }

              .remark-tag {
                font-size: 22rpx;
                color: $danger;
                background: #fff5e6;
                padding: 4rpx 12rpx;
                border-radius: 4rpx;
              }
            }
          }

          .price-item {
            display: grid;
            grid-template-columns: 1fr 1.5fr;
            align-items: center;
            padding: 10rpx;
            border-bottom: 2rpx solid #eee;
            gap: 20rpx;

            .color-name {
              font-size: 24rpx;
              color: #333;
              grid-column: 1 / 2;
              width: 100%;
              min-width: 0;
            }

            .price-info {
              display: grid;
              grid-template-columns: 1fr 1fr;
              grid-column: 2 / 3;
              gap: 20rpx;
              width: 100%;
              min-width: 0;

              &.not-updated {
                opacity: 0.5;
              }

              .price-value {
                grid-column: 1 / 2;
                padding: 4rpx 16rpx;
                text-align: center;
                background: #F7F7F7;
                font-size: 24rpx;
                color: #333;

                &.not-updated {
                  color: #999;
                }
              }

              .price-change {
                grid-column: 2 / 3;
                display: flex;
                align-items: center;
                justify-content: flex-end;
                gap: 8rpx;

                .change-value {
                  text-align: right;
                  font-size: 24rpx;

                  &.up {
                    color: $danger;
                  }

                  &.down {
                    color: $green;
                  }

                  &.not-updated {
                    color: $gray;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .bottom-tip {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 56rpx;
    background: $light;
    line-height: 56rpx;
    text-align: center;
    font-size: 24rpx;
    color: #333333;
  }

  .dialog-content {
    padding: 20rpx 40rpx;

    .history-item {
      display: flex;
      justify-content: space-between;
      padding: 10rpx 0;
      font-size: 24rpx;
      color: #7d7e80;
    }
  }
}
</style>
